import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/modules/devices/views/pop_field_view.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:mziot/generated/assets.dart';
import 'package:mziot/generated/locales.g.dart';

import '../controllers/device_manager_controller.dart';

class DeviceManagerView extends GetView<DeviceManagerController> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        if (controller.bluetoothDevice != null) {
          Get.back(result: 0);
        } else {
          Get.back(result: true);
        }
        return Future.value(true);
      },
      child: Scaffold(
        extendBodyBehindAppBar: true,
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: Obx(() {
            return Text(controller.infoName.value);
          }),
          systemOverlayStyle: SystemUiOverlayStyle.dark,
          elevation: 1,
          shadowColor: MColor.xFFCCCCCC.withAlpha(80),
        ),
        body: SafeArea(
          bottom: false,
          child: Container(
            width: double.infinity,
            color: MColor.xFFEFF4FB,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                  color: Colors.white,
                  child: Column(
                    children: [
                      SizedBox(height: 24),
                      _iconView,
                      _nameView,
                      SizedBox(height: 23),
                    ],
                  ),
                ),
                SizedBox(height: 8),
                _chooseView(true, false),
                if (controller.isGroup) ...{
                  _chooseView(true, true),
                },
                Obx(() {
                  final show = controller.isNetDevice.value;
                  if (show) {
                    return _chooseView(false, false);
                  }
                  return Container();
                }),
                Spacer(),
                !controller.isGroup && controller.isAdd ? _addBottomView : _bottomView,
              ],
            ),
          ),
        ),
      ),
    );
  }

  get _iconView {
    if (controller.isGroup) {
      return Image.asset(
        Assets.imagesDeviceGroupIcon,
        width: 100,
        height: 100,
      );
    }
    return Obx(() {
      if (controller.productImage.value.isEmpty) {
        return Container(
          width: 100,
          height: 100,
        );
      }
      return CachedNetworkImage(
        imageUrl: controller.productImage.value,
        width: 100,
        height: 100,
        placeholder: (ctx, _) {
          return Container(
            width: 100,
            height: 100,
            decoration: BoxDecoration(
              color: MColor.xFFCCCCCC,
              borderRadius: BorderRadius.circular(8),
            ),
          );
        },
      );
    });
  }

  get _nameView {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {},
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Obx(() {
            var name = controller.infoName.value;
            if (name == LocaleKeys.add_devices_group_title.tr) {
              name = LocaleKeys.add_devices_group_name.tr;
            }
            return Text(
              name,
            );
          }),
          SizedBox(width: 4),
          IconButton(
            padding: EdgeInsets.zero,
            alignment: Alignment.centerLeft,
            constraints: BoxConstraints(maxWidth: 16),
            onPressed: () {
              Get.dialog(
                PopFiledView((name) {
                  controller.infoName.value = name;
                }),
                useSafeArea: false,
              );
            },
            icon: Image.asset(
              Assets.imagesDeviceEdit,
              width: 16,
              height: 16,
            ),
          ),
        ],
      ),
    );
  }

  Widget _chooseView(bool isChoose, bool chooseDevice) {
    var text = controller.isGroup
        ? chooseDevice
            ? LocaleKeys.devices_choose_device_title.tr
            : LocaleKeys.devices_choose_scene.tr
        : LocaleKeys.add_devices_choose_group.tr;
    if (!isChoose) {
      text = LocaleKeys.devices_wifi.tr;
    }
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        if (isChoose) {
          controller.openChooseAction(chooseDevice);
        } else {
          final id = controller.deviceInfo?.id ?? 0;
          Get.offNamed(Routes.WIFI,
              arguments: controller.deviceInfo, parameters: {'id': id.toString()});
        }
      },
      child: Container(
        padding: EdgeInsets.only(left: 12, right: 12, top: 8),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(bottom: BorderSide(color: MColor.xFFEEEEEE)),
        ),
        height: 50,
        child: Row(
          children: [
            Text(
              text,
              style: MFont.regular13.apply(color: MColor.xFF333333),
            ),
            if (isChoose) ...{
              Expanded(
                child: Obx(() {
                  var text = LocaleKeys.devices_choose.tr;
                  if (chooseDevice && controller.deviceText.value.isNotEmpty) {
                    text = controller.deviceText.value;
                  } else if (controller.selectText.value.isNotEmpty && !chooseDevice) {
                    text = controller.selectText.value;
                  }
                  return Text(
                    text,
                    style: MFont.regular13
                        .apply(color: MColor.xFF999999, overflow: TextOverflow.ellipsis),
                    maxLines: 1,
                    textAlign: TextAlign.end,
                  );
                }),
              ),
              SizedBox(width: 6),
            } else ...{
              Spacer(),
            },
            Icon(
              Icons.arrow_forward_ios,
              size: 15,
              color: MColor.xFF999999.withAlpha(90),
            ),
          ],
        ),
      ),
    );
  }

  get _addBottomView {
    return Container(
      width: double.infinity,
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: SafeArea(
        top: false,
        child: Container(
          child: TextButton(
            style: ButtonStyle(
              shape: MaterialStateProperty.all(StadiumBorder()),
              backgroundColor: MaterialStateProperty.all(MColor.skin),
            ),
            onPressed: () {
              throttle(() {
                controller.fetchAddDevice();
              });
            },
            child: Obx(() {
              return controller.isLoading.value
                  ? loadingWidget
                  : Text(
                      LocaleKeys.add_devices_activation.tr,
                      style: MFont.regular15.apply(color: MColor.xFFEEEEEE),
                    );
            }),
          ),
        ),
      ),
    );
  }

  get _bottomView {
    return Container(
      color: Colors.white,
      child: SafeArea(
        top: false,
        child: Container(
          height: 49,
          child: Row(
            children: [
              SizedBox(width: 48),
              Expanded(
                child: TextButton(
                  onPressed: () {
                    Get.back(result: true);
                  },
                  style: ButtonStyle(
                    shape: MaterialStateProperty.all(StadiumBorder()),
                    backgroundColor: MaterialStateProperty.all(MColor.xFFF2F2F2),
                  ),
                  child: Text(
                    LocaleKeys.devices_cancel.tr,
                    style: MFont.regular13.apply(color: MColor.xFF333333),
                  ),
                ),
              ),
              SizedBox(width: 16),
              Expanded(
                child: TextButton(
                  onPressed: () {
                    throttle(() {
                      if (controller.isGroup) {
                        controller.fetchAddGroup();
                      } else {
                        controller.fetchEditDevice();
                      }
                    });
                  },
                  style: ButtonStyle(
                    shape: MaterialStateProperty.all(StadiumBorder()),
                    backgroundColor: MaterialStateProperty.all(MColor.skin),
                  ),
                  child: Obx(() {
                    return controller.isLoading.value
                        ? loadingWidget
                        : Text(
                            LocaleKeys.public_save.tr,
                            style: MFont.regular13.apply(color: Colors.white),
                          );
                  }),
                ),
              ),
              SizedBox(width: 48),
            ],
          ),
        ),
      ),
    );
  }
}
